let main, receiver, filter;
let _codeQueryTag = false; // 标记变量

export const initScan = () => {

	main = plus.android.runtimeMainActivity(); // 获取主 activity
	var IntentFilter = plus.android.importClass("android.content.IntentFilter");
	filter = new IntentFilter();
	const action = uni.getStorageSync('currentDeviceData').action // 获取动作
	const stringExtra = uni.getStorageSync('currentDeviceData').stringExtra // 获取字符串额外参数
	filter.addAction(action); // 添加广播动作
	receiver = plus.android.implements(
		"io.dcloud.feature.internal.reflect.BroadcastReceiver", {
			onReceive: function(context, intent) {
				plus.android.importClass(intent);
				let code = intent.getStringExtra(stringExtra); // 获取广播中的字符串额外参数
				queryCode(code);
			},
		}
	);
};


export const startScan = () => {
	main.registerReceiver(receiver, filter); // 开始监听广播
};
export const stopScan = () => {
	main.unregisterReceiver(receiver); // 停止监听广播
	// 解绑 uni 全局事件监听器，否则可能会出错
	uni.$off('SCAN_CODE');
};
export const queryCode = (code) => {
	// 防止重复查询
	if (_codeQueryTag) return false;
	_codeQueryTag = true; // 标记为已经查询
	setTimeout(function() {
		_codeQueryTag = false; // 重置标记
	}, 150);
	var id = code;
	//id 就是扫码的结果
	uni.$emit("SCAN_CODE", {
		code: id
	}); // 触发 SCAN_CODE 事件，并传递扫描到的内容
};